package multiThreading;

import javafx.scene.chart.BarChart;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class netBar implements Runnable {
    private boolean tag = true;//网管开始营业
    private DelayQueue<persons> q = new DelayQueue<>();//定义一个队列，装那些在网吧上网的人

    public static void main(String arg[]) {
        netBar p = new netBar();
        System.out.println("网吧开始上班");
        Thread pup = new Thread(p);
        p.up(10, "Messi", 10);
        p.up(7, "Ronaldo", 7);
        p.up(8, "Xavi", 8);
        pup.start();
    }

    public void up(int id, String name, int money) {//表示上网开始
        persons person = new persons(id, name, money * 1000 + System.currentTimeMillis());//currentTimeMillis()返回值
        q.add(person);//把这个人加入到队列中
        System.out.println(name + " 身份证：" + id + "，交了" + money + "块钱，开始上网");
    }

    public void down(persons person) {
        System.out.println(person.getName() + "身份证" + person.getId() + "上网结束，下线");
    }

    @Override
    public void run() {
        while (tag) {//网管开始上班
            try {
                persons person = q.take();//取出网吧中在上网的人
                down(person);
                tag = q.isEmpty() ? false : true;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class persons implements Delayed {
    private String name;//上网者的名字
    private int id;//上网者的身份证
    private long endtime;//上网者的结束时间

    public persons(int id, String name, long endtime) {
        this.id = id;
        this.name = name;
        this.endtime = endtime;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return this.endtime - System.currentTimeMillis();//返回当前上网者还剩余的时间
    }

    @Override
    public int compareTo(Delayed o) {//用于找出谁上网的时间长
        persons that = (persons) o;
        return (int) (this.getDelay(TimeUnit.SECONDS) - that.getDelay(TimeUnit.SECONDS));//要转一下单位，
    }

    public String getName() {
        return name;
    }


    public int getId() {
        return id;
    }

}
